package com.aididi.consumer;

import com.aididi.entity.Order;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author xuzexiang
 * @Date: 2018-10-21 0021
 * @Description:    消费者	durable=true（持久化）
 */ 
@Component
@Slf4j
public class OrderConsumer {

	/**
	*	@Payload(消息体)	@Headers(消息头)   
	*/
    @RabbitListener(bindings =@QueueBinding(value = @Queue(value = "order-queue",durable = "true"),
            exchange = @Exchange(value = "order-exchange",durable = "true",type ="topic" ),
            key = "order.#"))
    @RabbitHandler
    public void  receive(@Payload Order order,
                        @Headers Map<String,Object> map,
                         Channel channel){
        System.out.println("-----接收消息-----");
        System.out.println("订单id"+order.getMessageId());
        Long tag = (Long) map.get(AmqpHeaders.DELIVERY_TAG);
        try {
            /**
             *  手工ack认证
             *deliveryTag（唯一标识 ID）：当一个消费者向 RabbitMQ 注册后，会建立起一个Channel ，
             * RabbitMQ 会用 basic.deliver 方法向消费者推送消息，这个方法携带了一个delivery tag， 它代表了 RabbitMQ 向该 Channel 投递的这条消息的唯一标识 ID，
             * 是一个单调递增的正整数，delivery tag 的范围仅限于 Channel
             *
             * multiple：为了减少网络流量，手动确认可以被批处理，当该参数为 true 时，则可以一次性确认 delivery_tag 小于等于传入值的所有消息
             */
            log.info("deliveryTag:{}",tag);
            channel.basicAck(tag,false);
        } catch (Exception e){
            e.printStackTrace();
        }

    }

}
